

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="John Doe">
  <meta name="keywords" content="">
  
    <meta name="description" content="@[toc]  Flask 是一个使用 Python 编写的轻量级 Web 应用程序框架。接下来以初学者的角度来编写后端的接口，不涉及前端代码，即没有用到 Flask 的模板渲染。 运行环境：  windows11 PyCharm 专业版 2021.3 MySQL 5.7.36 Navicat 15 数据库管理工具 Postman 接口请求工具 Anaconda 3  python 3.8 fla">
<meta property="og:type" content="article">
<meta property="og:title" content="Python Web 开发 _ Flask 简单实现用户注册、登录、注销、查询接口 _ 初学者案例 _ 简单封装响应数据 _ 使用 Postman 进行接口测试.">
<meta property="og:url" content="http://example.com/2022/08/04/Python%20Web%20%E5%BC%80%E5%8F%91%20_%20Flask%20%E7%AE%80%E5%8D%95%E5%AE%9E%E7%8E%B0%E7%94%A8%E6%88%B7%E6%B3%A8%E5%86%8C%E3%80%81%E7%99%BB%E5%BD%95%E3%80%81%E6%B3%A8%E9%94%80%E3%80%81%E6%9F%A5%E8%AF%A2%E6%8E%A5%E5%8F%A3%20_%20%E5%88%9D%E5%AD%A6%E8%80%85%E6%A1%88%E4%BE%8B%20_%20%E7%AE%80%E5%8D%95%E5%B0%81%E8%A3%85%E5%93%8D%E5%BA%94%E6%95%B0%E6%8D%AE%20_%20%E4%BD%BF%E7%94%A8%20Postman%20%E8%BF%9B%E8%A1%8C%E6%8E%A5%E5%8F%A3%E6%B5%8B%E8%AF%95/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="@[toc]  Flask 是一个使用 Python 编写的轻量级 Web 应用程序框架。接下来以初学者的角度来编写后端的接口，不涉及前端代码，即没有用到 Flask 的模板渲染。 运行环境：  windows11 PyCharm 专业版 2021.3 MySQL 5.7.36 Navicat 15 数据库管理工具 Postman 接口请求工具 Anaconda 3  python 3.8 fla">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-08-03T18:33:19.000Z">
<meta property="article:modified_time" content="2022-08-22T15:47:32.424Z">
<meta property="article:author" content="John Doe">
<meta property="article:tag" content="Python">
<meta property="article:tag" content="Flask">
<meta name="twitter:card" content="summary_large_image">
  
  
  
  <title>Python Web 开发 _ Flask 简单实现用户注册、登录、注销、查询接口 _ 初学者案例 _ 简单封装响应数据 _ 使用 Postman 进行接口测试. - Hexo</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>尤 Ni&#39;s Blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="Python Web 开发 _ Flask 简单实现用户注册、登录、注销、查询接口 _ 初学者案例 _ 简单封装响应数据 _ 使用 Postman 进行接口测试."></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        John Doe
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-08-04 02:33" pubdate>
          2022年8月4日 凌晨
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          10k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          85 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Python Web 开发 _ Flask 简单实现用户注册、登录、注销、查询接口 _ 初学者案例 _ 简单封装响应数据 _ 使用 Postman 进行接口测试.</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：1 小时前
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <p>@[toc]</p>
<hr>
<p><a target="_blank" rel="noopener" href="https://flask.net.cn/">Flask</a> 是一个使用 Python 编写的轻量级 Web 应用程序框架。接下来以初学者的角度来编写后端的接口，不涉及前端代码，即没有用到 Flask 的模板渲染。</p>
<p><strong>运行环境：</strong></p>
<ul>
<li>windows11</li>
<li>PyCharm 专业版 2021.3</li>
<li>MySQL 5.7.36</li>
<li>Navicat 15 数据库管理工具</li>
<li>Postman 接口请求工具</li>
<li>Anaconda 3 </li>
<li>python 3.8</li>
<li>flask 2.2.0 </li>
<li>flask_sqlalchemy 2.5.1 ，flask 框架支持ORM 数据持久化的库</li>
</ul>
<p>案例的文件结构：<br>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/1c98f4aa65684b16b26b5519f21e2c89.png#">https://img-blog.csdnimg.cn/1c98f4aa65684b16b26b5519f21e2c89.png#</a> &#x3D;50%x)</p>
<h1 id="一、前置准备"><a href="#一、前置准备" class="headerlink" title="一、前置准备"></a>一、前置准备</h1><h2 id="1-1-创建数据表"><a href="#1-1-创建数据表" class="headerlink" title="1.1 创建数据表"></a>1.1 创建数据表</h2><p>本次小案例，只用到一张用户表 sys_user</p>
<p>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/bde9ef6e15904de8b2383dbfda6e9091.png#">https://img-blog.csdnimg.cn/bde9ef6e15904de8b2383dbfda6e9091.png#</a> &#x3D;70%x)</p>
<p>建表的 MySQL 语句：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-keyword">SET</span> NAMES utf8mb4;<br><span class="hljs-keyword">SET</span> FOREIGN_KEY_CHECKS <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;<br><br><span class="hljs-comment">-- ----------------------------</span><br><span class="hljs-comment">-- Table structure for sys_user</span><br><span class="hljs-comment">-- ----------------------------</span><br><span class="hljs-keyword">DROP</span> <span class="hljs-keyword">TABLE</span> IF <span class="hljs-keyword">EXISTS</span> `sys_user`;<br><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> `sys_user`  (<br>  `user_id` <span class="hljs-type">int</span>(<span class="hljs-number">11</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-keyword">NULL</span> AUTO_INCREMENT,<br>  `user_name` <span class="hljs-type">varchar</span>(<span class="hljs-number">255</span>) <span class="hljs-type">CHARACTER</span> <span class="hljs-keyword">SET</span> utf8mb4 <span class="hljs-keyword">COLLATE</span> utf8mb4_general_ci <span class="hljs-keyword">NULL</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-keyword">NULL</span>,<br>  `user_password` <span class="hljs-type">varchar</span>(<span class="hljs-number">255</span>) <span class="hljs-type">CHARACTER</span> <span class="hljs-keyword">SET</span> utf8mb4 <span class="hljs-keyword">COLLATE</span> utf8mb4_general_ci <span class="hljs-keyword">NULL</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-keyword">NULL</span>,<br>  <span class="hljs-keyword">PRIMARY</span> KEY (`user_id`) <span class="hljs-keyword">USING</span> BTREE,<br>  <span class="hljs-keyword">UNIQUE</span> INDEX `user_name`(`user_name`) <span class="hljs-keyword">USING</span> BTREE COMMENT <span class="hljs-string">&#x27;用户名称不可重复&#x27;</span><br>) ENGINE <span class="hljs-operator">=</span> InnoDB AUTO_INCREMENT <span class="hljs-operator">=</span> <span class="hljs-number">8</span> <span class="hljs-type">CHARACTER</span> <span class="hljs-keyword">SET</span> <span class="hljs-operator">=</span> utf8mb4 <span class="hljs-keyword">COLLATE</span> <span class="hljs-operator">=</span> utf8mb4_general_ci ROW_FORMAT <span class="hljs-operator">=</span> <span class="hljs-keyword">Dynamic</span>;<br><br><span class="hljs-comment">-- ----------------------------</span><br><span class="hljs-comment">-- Records of sys_user</span><br><span class="hljs-comment">-- ----------------------------</span><br><span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> `sys_user` <span class="hljs-keyword">VALUES</span> (<span class="hljs-number">1</span>, <span class="hljs-string">&#x27;小王&#x27;</span>, <span class="hljs-string">&#x27;123456&#x27;</span>);<br><span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> `sys_user` <span class="hljs-keyword">VALUES</span> (<span class="hljs-number">2</span>, <span class="hljs-string">&#x27;小绿&#x27;</span>, <span class="hljs-string">&#x27;123456&#x27;</span>);<br><span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> `sys_user` <span class="hljs-keyword">VALUES</span> (<span class="hljs-number">3</span>, <span class="hljs-string">&#x27;uni&#x27;</span>, <span class="hljs-string">&#x27;123456&#x27;</span>);<br><br><span class="hljs-keyword">SET</span> FOREIGN_KEY_CHECKS <span class="hljs-operator">=</span> <span class="hljs-number">1</span>;<br></code></pre></td></tr></table></figure>


<h2 id="1-2-修改-Postman-的请求头"><a href="#1-2-修改-Postman-的请求头" class="headerlink" title="1.2 修改 Postman 的请求头"></a>1.2 修改 Postman 的请求头</h2><p>最后在进行接口测试时，需要通过 JSON 传值，这里需要指定为 application&#x2F;json; 的格式，为避免出现中文乱码，最好加上charset&#x3D;utf8<br>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/1e4db6d5396b430a8f1315553fd6d106.png#">https://img-blog.csdnimg.cn/1e4db6d5396b430a8f1315553fd6d106.png#</a> &#x3D;80%x)</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs python">Content-<span class="hljs-type">Type</span> = application/json;charset=utf8<br></code></pre></td></tr></table></figure>
<h1 id="二、具体实现"><a href="#二、具体实现" class="headerlink" title="二、具体实现"></a>二、具体实现</h1><h2 id="2-1-utils-py"><a href="#2-1-utils-py" class="headerlink" title="2.1 utils.py"></a>2.1 utils.py</h2><p>Flask 框架在处理请求后，返回的数据必须是可转化为JSON的类型，即字典类型。此工具文件中的方法支持将列表里的所有 User 对象转化到 dict 字典中，其中的 key 为下标，value 则为 Use对象调用 dict() 的结果，这个方法是自定义的，待会在 models.py 里会说明。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">    将列表里的对象逐一转化为字典, 对象需提供 dict 方法</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">model_list_to_dict</span>(<span class="hljs-params">modelList: <span class="hljs-built_in">list</span></span>):<br>    result = &#123;&#125;<br>    <span class="hljs-keyword">for</span> index, model <span class="hljs-keyword">in</span> <span class="hljs-built_in">enumerate</span>(modelList):<br>        result.update(&#123;index: model.<span class="hljs-built_in">dict</span>()&#125;)<br>    <span class="hljs-keyword">return</span> result<br><br></code></pre></td></tr></table></figure>

<h2 id="2-2-mysql-py"><a href="#2-2-mysql-py" class="headerlink" title="2.2 mysql.py"></a>2.2 mysql.py</h2><p>该脚本只是创建了 SQLAlchemy() 对象，至于为什么将它单独放在这个文件里，是因为后面的 models.py 和 app.py 都将用到它，这里类似单例模式的设计，是为了防止重复创建 SQLAlchemy() 对象</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">from</span> flask_sqlalchemy <span class="hljs-keyword">import</span> SQLAlchemy<br>db = SQLAlchemy()<br></code></pre></td></tr></table></figure>

<h2 id="2-3-models-py"><a href="#2-3-models-py" class="headerlink" title="2.3 models.py"></a>2.3 models.py</h2><p>Flask 框架中 flask_sqlalchemy 库 支持数据库的交互，使用前需定义数据库中表的对应类，该类的特点有：</p>
<ul>
<li>必须继承 SQLAlchemy() 对象中的 Model</li>
<li>必须指定表名，<code>__tablename__</code> </li>
<li>定义字段对应的变量必须是静态变量，且需调用 SQLAlchemy() 对象的  Column 方法</li>
</ul>
<p>这里的 dict() 方法是我自定义的，个人觉得这样比较方便，在 Flask 返回数据时必须是能转化成 JSON 的字符串，同时在输出时也方便查看，相当于 Java 的 toString </p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">from</span> mysql <span class="hljs-keyword">import</span> db<br><br><span class="hljs-string">&quot;&quot;&quot;--------------------------------------</span><br><span class="hljs-string">            定义 MySQL 用户的映射类</span><br><span class="hljs-string">-----------------------------------------&quot;&quot;&quot;</span><br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">User</span>(db.Model):<br>    __tablename__ = <span class="hljs-string">&quot;sys_user&quot;</span><br>    <span class="hljs-built_in">id</span> = db.Column(db.Integer, name=<span class="hljs-string">&#x27;user_id&#x27;</span>, primary_key=<span class="hljs-literal">True</span>)<br>    name = db.Column(db.String, name=<span class="hljs-string">&#x27;user_name&#x27;</span>, unique=<span class="hljs-literal">True</span>)<br>    password = db.Column(db.String, name=<span class="hljs-string">&#x27;user_password&#x27;</span>)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">dict</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-keyword">return</span> &#123;<br>            <span class="hljs-string">&#x27;id&#x27;</span>: self.<span class="hljs-built_in">id</span>,<br>            <span class="hljs-string">&#x27;name&#x27;</span>: self.name,<br>            <span class="hljs-string">&#x27;password&#x27;</span>: self.password<br>        &#125;<br></code></pre></td></tr></table></figure>
<h2 id="2-4-entity-py"><a href="#2-4-entity-py" class="headerlink" title="2.4 entity.py"></a>2.4 entity.py</h2><p>前后端交互响应类 r ，在接口返回数据时调用，其实直接调用 flask 提供的 jsonify()方法就行，这里自定义一个 r，作用是为了指定默认的参数，比如指定 code &#x3D; 200，默认为 200 响应代码，表示响应成功。除此之外，我们返回的 r 是继承于 python内置的** dict 字典 **的，支持转化为 JSON 格式的数据。<br>这种返回的 r 一定会存在 code、msg 和 data 这三个 key，方便前端对接口响应的数据进行判断与处理。<br>jsonify 是备用的，如果出现报错，再调用 flask 提供的这个方法。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">from</span> flask <span class="hljs-keyword">import</span> jsonify<br><span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">    前后端交互响应类</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">r</span>(<span class="hljs-title class_ inherited__">dict</span>):<br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self, code=<span class="hljs-number">200</span>, msg=<span class="hljs-string">&#x27;空&#x27;</span>, data=<span class="hljs-literal">None</span></span>):<br>        <span class="hljs-built_in">super</span>().__init__(code=code, msg=msg, data=data)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">jsonify</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-keyword">return</span> jsonify(self)<br></code></pre></td></tr></table></figure>

<h2 id="2-5-app-py"><a href="#2-5-app-py" class="headerlink" title="2.5 app.py"></a>2.5 app.py</h2><p>app.py 是创建 Flask 实例 以及编写 API 接口的主要实现的文件，这里其实应该可以分为两个文件，由于是初学就暂时不分那么清晰。<br>代码看起来比较长，但逻辑是很清楚的，先创建 Flask 实例，使用 pymysql 加载 mysql 引擎，通过 Flask 实例对象配置 MySQL 连接的 URL（URL里包含了数据库的账号和密码），使用 @app.route() 标记负责响应请求的类，可以类比 SpringMVC 里的 Controller。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">from</span> flask <span class="hljs-keyword">import</span> Flask, request, session<br><span class="hljs-keyword">from</span> typing <span class="hljs-keyword">import</span> <span class="hljs-type">List</span><br><span class="hljs-keyword">from</span> mysql <span class="hljs-keyword">import</span> db<br><span class="hljs-keyword">from</span> models <span class="hljs-keyword">import</span> User<br><span class="hljs-keyword">from</span> utils <span class="hljs-keyword">import</span> model_list_to_dict  <span class="hljs-comment"># 自定义的 utils 工具包</span><br><span class="hljs-keyword">import</span> pymysql<br><span class="hljs-keyword">from</span> entity <span class="hljs-keyword">import</span> r<br><br><span class="hljs-comment"># 创建 Flask 实例</span><br>app = Flask(__name__)<br><br><span class="hljs-string">&quot;&quot;&quot;----------------------------------------</span><br><span class="hljs-string">                初始化 Flask </span><br><span class="hljs-string">-------------------------------------------&quot;&quot;&quot;</span><br><span class="hljs-comment"># 初始化数据库</span><br>pymysql.install_as_MySQLdb()<br><span class="hljs-comment"># 配置数据库</span><br>app.config[<span class="hljs-string">&#x27;SQLALCHEMY_DATABASE_URI&#x27;</span>] = <span class="hljs-string">&quot;mysql://root:woaini@localhost:3306/flask_test_db&quot;</span><br><span class="hljs-comment"># 解决中文乱码</span><br>app.config[<span class="hljs-string">&#x27;JSON_AS_ASCII&#x27;</span>] = <span class="hljs-literal">False</span><br><span class="hljs-comment"># 关闭</span><br>app.config[<span class="hljs-string">&#x27;SQLALCHEMY_TRACK_MODIFICATIONS&#x27;</span>] = <span class="hljs-literal">False</span><br><span class="hljs-comment"># 设置 session 密钥</span><br>app.config[<span class="hljs-string">&#x27;SECRET_KEY&#x27;</span>] = <span class="hljs-string">&#x27;I LIKE U&#x27;</span><br><span class="hljs-comment"># 初始化数据库</span><br>db.init_app(app)<br><br><br><span class="hljs-string">&quot;&quot;&quot;----------------------------------------</span><br><span class="hljs-string">                API: 初始化</span><br><span class="hljs-string">-------------------------------------------&quot;&quot;&quot;</span><br><span class="hljs-meta">@app.route(<span class="hljs-params"><span class="hljs-string">&#x27;/&#x27;</span>, methods=[<span class="hljs-string">&#x27;GET&#x27;</span>]</span>)</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">hello</span>():<br>    <span class="hljs-keyword">return</span> r(code=<span class="hljs-number">200</span>, msg=<span class="hljs-string">&#x27;服务器访问成功!&#x27;</span>)<br><br><br><span class="hljs-string">&quot;&quot;&quot;----------------------------------------</span><br><span class="hljs-string">                API: 查询所有用户</span><br><span class="hljs-string">-------------------------------------------&quot;&quot;&quot;</span><br><span class="hljs-meta">@app.route(<span class="hljs-params"><span class="hljs-string">&#x27;/user&#x27;</span>, methods=[<span class="hljs-string">&#x27;GET&#x27;</span>]</span>)</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">user_find_all</span>():<br>    userList: <span class="hljs-type">List</span>[User] = User.query.<span class="hljs-built_in">all</span>()<br>    <span class="hljs-keyword">return</span> r(code=<span class="hljs-number">200</span>, msg=<span class="hljs-string">&#x27;用户查询成功&#x27;</span>, data=model_list_to_dict(userList))<br><br><br><span class="hljs-string">&quot;&quot;&quot;----------------------------------------</span><br><span class="hljs-string">                API: 根据ID查询指定用户</span><br><span class="hljs-string">-------------------------------------------&quot;&quot;&quot;</span><br><span class="hljs-meta">@app.route(<span class="hljs-params"><span class="hljs-string">&#x27;/user/&lt;int:user_id&gt;&#x27;</span>, methods=[<span class="hljs-string">&#x27;GET&#x27;</span>]</span>)</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">user_find</span>(<span class="hljs-params">user_id</span>):<br>    user = User.query.get(user_id)<br>    <span class="hljs-keyword">if</span> user == <span class="hljs-literal">None</span>:<br>        <span class="hljs-keyword">return</span> r(code=<span class="hljs-number">200</span>, msg=<span class="hljs-string">&#x27;用户不存在&#x27;</span>)<br>    <span class="hljs-keyword">else</span>:<br>        <span class="hljs-keyword">return</span> r(code=<span class="hljs-number">200</span>, msg=<span class="hljs-string">&#x27;用户查询成功&#x27;</span>, data=user.<span class="hljs-built_in">dict</span>())<br><br><br><span class="hljs-string">&quot;&quot;&quot;----------------------------------------</span><br><span class="hljs-string">                API: 注册用户</span><br><span class="hljs-string">-------------------------------------------&quot;&quot;&quot;</span><br><span class="hljs-meta">@app.route(<span class="hljs-params"><span class="hljs-string">&#x27;/register&#x27;</span>, methods=[<span class="hljs-string">&#x27;POST&#x27;</span>]</span>)</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">user_register</span>():<br>    reqJSONData = request.get_json(silent=<span class="hljs-literal">True</span>)  <span class="hljs-comment"># 允许 请求体的 raw 为空</span><br>    <span class="hljs-comment"># 1. 处理请求参数为空</span><br>    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> reqJSONData: <span class="hljs-keyword">return</span> r(code=<span class="hljs-number">401</span>, msg=<span class="hljs-string">&#x27;注册失败, 请求参数为空&#x27;</span>)<br>    username = reqJSONData.get(<span class="hljs-string">&#x27;username&#x27;</span>)<br>    password = reqJSONData.get(<span class="hljs-string">&#x27;password&#x27;</span>)<br>    <span class="hljs-comment"># 2. 处理请求参数缺少</span><br>    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> <span class="hljs-built_in">all</span>([username, password]):<br>        <span class="hljs-keyword">return</span> r(code=<span class="hljs-number">401</span>, msg=<span class="hljs-string">&#x27;注册失败, 缺少请求参数&#x27;</span>, )<br>    <span class="hljs-comment"># 3. 根据 user_name 字段判断用户是否注册过</span><br>    <span class="hljs-keyword">try</span>:<br>        user = User.query.filter_by(name=username).first()<br>        <span class="hljs-keyword">if</span> user:<br>            <span class="hljs-keyword">return</span> r(code=<span class="hljs-number">401</span>, msg=<span class="hljs-string">&#x27;注册失败, 用户已存在&#x27;</span>)<br>    <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:<br>        <span class="hljs-built_in">print</span>(e, <span class="hljs-string">&#x27;[Error] in [/user] [POST] when select MYSQL user where name=[] .&#x27;</span>)<br>        <span class="hljs-keyword">return</span> r(code=<span class="hljs-number">402</span>, msg=<span class="hljs-string">&#x27;服务器内部出错&#x27;</span>)<br>    <span class="hljs-comment"># 4. 注册用户到数据库</span><br>    user = User(name=username, password=password)<br>    <span class="hljs-keyword">try</span>:<br>        db.session.add(user)<br>        db.session.commit()  <span class="hljs-comment"># 提交事务</span><br>    <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:<br>        db.session.rollback()  <span class="hljs-comment"># 异常时回滚</span><br>        <span class="hljs-built_in">print</span>(e, <span class="hljs-string">&#x27;[Error] in [/user] [POST] when inserting a user into MySQL.&#x27;</span>)<br>        <span class="hljs-keyword">return</span> r(code=<span class="hljs-number">402</span>, msg=<span class="hljs-string">&#x27;服务器内部出错&#x27;</span>)<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&#x27;新用户注册成功:  &#x27;</span>, user.<span class="hljs-built_in">dict</span>())<br>    <span class="hljs-keyword">return</span> r(code=<span class="hljs-number">200</span>, msg=<span class="hljs-string">&#x27;注册成功&#x27;</span>, data=user.<span class="hljs-built_in">dict</span>())<br><br><br><span class="hljs-string">&quot;&quot;&quot;----------------------------------------</span><br><span class="hljs-string">                API: 用户登录</span><br><span class="hljs-string">-------------------------------------------&quot;&quot;&quot;</span><br><span class="hljs-meta">@app.route(<span class="hljs-params"><span class="hljs-string">&#x27;/login&#x27;</span>, methods=[<span class="hljs-string">&#x27;POST&#x27;</span>]</span>)</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">user_login</span>():<br>    reqJSONData = request.get_json(silent=<span class="hljs-literal">True</span>)  <span class="hljs-comment"># 允许 请求体的 raw 为空</span><br>    <span class="hljs-comment"># 1. 处理请求参数为空</span><br>    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> reqJSONData: <span class="hljs-keyword">return</span> r(code=<span class="hljs-number">401</span>, msg=<span class="hljs-string">&#x27;注册失败, 请求参数为空&#x27;</span>)<br>    username = reqJSONData.get(<span class="hljs-string">&#x27;username&#x27;</span>)<br>    password = reqJSONData.get(<span class="hljs-string">&#x27;password&#x27;</span>)<br>    <span class="hljs-comment"># 2. 处理请求参数缺少</span><br>    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> <span class="hljs-built_in">all</span>([username, password]):<br>        <span class="hljs-keyword">return</span> r(code=<span class="hljs-number">401</span>, msg=<span class="hljs-string">&#x27;登录, 缺少请求参数&#x27;</span>)<br>    <span class="hljs-comment"># 3. 验证账号和密码</span><br>    user = User.query.filter_by(name=username, password=password).first()<br>    <span class="hljs-comment"># 4. 用户不存在, 直接返回</span><br>    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> user:<br>        <span class="hljs-keyword">return</span> r(code=<span class="hljs-number">404</span>, msg=<span class="hljs-string">&#x27;用户名或密码错误&#x27;</span>)<br>    <span class="hljs-keyword">else</span>:<br>        <span class="hljs-comment"># 5. 保存用户状态到 session</span><br>        session[<span class="hljs-string">&#x27;user_info&#x27;</span>] = user.<span class="hljs-built_in">dict</span>()<br>        <span class="hljs-keyword">return</span> r(msg=<span class="hljs-string">&#x27;登录成功&#x27;</span>, data=user.<span class="hljs-built_in">dict</span>())<br><br><br><span class="hljs-string">&quot;&quot;&quot;----------------------------------------</span><br><span class="hljs-string">                API: 验证用户状态</span><br><span class="hljs-string">-------------------------------------------&quot;&quot;&quot;</span><br><span class="hljs-meta">@app.route(<span class="hljs-params"><span class="hljs-string">&#x27;/login&#x27;</span>, methods=[<span class="hljs-string">&#x27;GET&#x27;</span>]</span>)</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">user_check_login</span>():<br>    userDict = session.get(<span class="hljs-string">&#x27;user_info&#x27;</span>)<br>    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> userDict:<br>        <span class="hljs-keyword">return</span> r(code=<span class="hljs-number">401</span>, msg=<span class="hljs-string">&#x27;未登录&#x27;</span>)<br>    <span class="hljs-keyword">else</span>:<br>        <span class="hljs-keyword">return</span> r(msg=<span class="hljs-string">&#x27;用户已登录&#x27;</span>, data=userDict)<br><br><br><span class="hljs-string">&quot;&quot;&quot;----------------------------------------</span><br><span class="hljs-string">                API: 注销登录</span><br><span class="hljs-string">-------------------------------------------&quot;&quot;&quot;</span><br><span class="hljs-meta">@app.route(<span class="hljs-params"><span class="hljs-string">&#x27;/logout&#x27;</span>, methods=[<span class="hljs-string">&#x27;GET&#x27;</span>]</span>)</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">user_logout</span>():<br>    userDict = session.get(<span class="hljs-string">&#x27;user_info&#x27;</span>)<br>    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> userDict:<br>        <span class="hljs-keyword">return</span> r(msg=<span class="hljs-string">&#x27;暂未登录&#x27;</span>)<br>    session.pop(<span class="hljs-string">&quot;user_info&quot;</span>)<br>    <span class="hljs-keyword">return</span> r(msg=<span class="hljs-string">&#x27;操作成功&#x27;</span>, data=userDict)<br><br><br><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">&#x27;__main__&#x27;</span>:<br>    app.run(host=<span class="hljs-string">&#x27;localhost&#x27;</span>, port=<span class="hljs-number">8081</span>, debug=<span class="hljs-literal">True</span>)<br><br></code></pre></td></tr></table></figure>
<h1 id="三、Postman-测试接口"><a href="#三、Postman-测试接口" class="headerlink" title="三、Postman 测试接口"></a>三、Postman 测试接口</h1><p>在 app.py 中的 128 行，设置的端口为 8081，启动 app.py 后访问 localhost:8081 </p>
<h2 id="3-1-测试访问接口"><a href="#3-1-测试访问接口" class="headerlink" title="3.1 测试访问接口"></a>3.1 测试访问接口</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs python">[GET]<br>/ <br></code></pre></td></tr></table></figure>
<p>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/b17f670bb62f4629b8a5308090800c41.png#">https://img-blog.csdnimg.cn/b17f670bb62f4629b8a5308090800c41.png#</a> &#x3D;80%x)</p>
<h2 id="3-2-测试注册接口"><a href="#3-2-测试注册接口" class="headerlink" title="3.2 测试注册接口"></a>3.2 测试注册接口</h2><p>注册接口处理了四种不同的情况：1）参数为空；2）缺少参数；3）用户名重复；4）注册成功，接下来逐一测试</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs python">[POST]<br>/register<br></code></pre></td></tr></table></figure>
<h3 id="3-2-1-参数为空"><a href="#3-2-1-参数为空" class="headerlink" title="3.2.1 参数为空"></a>3.2.1 参数为空</h3><p>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/dbf347f2468541c98a0f947f8e101e1a.png#">https://img-blog.csdnimg.cn/dbf347f2468541c98a0f947f8e101e1a.png#</a> &#x3D;70%x)</p>
<h3 id="3-2-2-缺少参数"><a href="#3-2-2-缺少参数" class="headerlink" title="3.2.2 缺少参数"></a>3.2.2 缺少参数</h3><p>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/a938aa48f5db4ba0a1ab769a769a3949.png#">https://img-blog.csdnimg.cn/a938aa48f5db4ba0a1ab769a769a3949.png#</a> &#x3D;70%x)</p>
<h3 id="3-2-3-用户名重复"><a href="#3-2-3-用户名重复" class="headerlink" title="3.2.3 用户名重复"></a>3.2.3 用户名重复</h3><p>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/df8216a7777f45c9abdd7b07090eeffb.png#">https://img-blog.csdnimg.cn/df8216a7777f45c9abdd7b07090eeffb.png#</a> &#x3D;80%x)</p>
<h3 id="3-2-4-注册成功"><a href="#3-2-4-注册成功" class="headerlink" title="3.2.4 注册成功"></a>3.2.4 注册成功</h3><p>根据 MySQL 数据表设计，用户ID字段 user_id 是自动递增的，这里由于我之前测试的时候添加过几条数据，然后又删除了，所以新注册后的用户 ID 变成了之前7的下一个 ，问题不大，能注册就OK<br>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/905a57b57b814b55af15e2ff39711ad4.png#">https://img-blog.csdnimg.cn/905a57b57b814b55af15e2ff39711ad4.png#</a> &#x3D;80%x)</p>
<h2 id="3-3-测试登录接口"><a href="#3-3-测试登录接口" class="headerlink" title="3.3 测试登录接口"></a>3.3 测试登录接口</h2><p>登录有两种情况：1）缺少参数；2）登录失败；3）登录成功</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs python">[POST]<br>/login<br></code></pre></td></tr></table></figure>
<h3 id="3-3-1-缺少参数"><a href="#3-3-1-缺少参数" class="headerlink" title="3.3.1 缺少参数"></a>3.3.1 缺少参数</h3><p>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/43b7b74cfb7941009f7d58ebb050df3f.png#">https://img-blog.csdnimg.cn/43b7b74cfb7941009f7d58ebb050df3f.png#</a> &#x3D;70%x)</p>
<h3 id="3-3-2-用户名或密码错误"><a href="#3-3-2-用户名或密码错误" class="headerlink" title="3.3.2 用户名或密码错误"></a>3.3.2 用户名或密码错误</h3><p>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/c1f6c001a3894462b7e3b7cb90a102ec.png#">https://img-blog.csdnimg.cn/c1f6c001a3894462b7e3b7cb90a102ec.png#</a> &#x3D;70%x)</p>
<h3 id="3-3-3-登录成功"><a href="#3-3-3-登录成功" class="headerlink" title="3.3.3 登录成功"></a>3.3.3 登录成功</h3><p>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/b461c2da9e4442568c10cf31cbb62458.png#">https://img-blog.csdnimg.cn/b461c2da9e4442568c10cf31cbb62458.png#</a> &#x3D;70%x)</p>
<h2 id="3-4-测试用户注销接口"><a href="#3-4-测试用户注销接口" class="headerlink" title="3.4 测试用户注销接口"></a>3.4 测试用户注销接口</h2><p>注销有两种情况：1）操作成功；2）暂未登录</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs python">[GET]<br>/logout<br></code></pre></td></tr></table></figure>
<h3 id="3-4-1-操作成功"><a href="#3-4-1-操作成功" class="headerlink" title="3.4.1 操作成功"></a>3.4.1 操作成功</h3><p>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/5eaec2d53f43450faf95dcaa22c1eb98.png#">https://img-blog.csdnimg.cn/5eaec2d53f43450faf95dcaa22c1eb98.png#</a> &#x3D;70%x)</p>
<h3 id="3-4-2-暂未登录"><a href="#3-4-2-暂未登录" class="headerlink" title="3.4.2 暂未登录"></a>3.4.2 暂未登录</h3><p>注销时若未登录则提示，返回代码依旧为 200，表示操作成功<br>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/a0bde95a9064435d9882861ef0ec1748.png#">https://img-blog.csdnimg.cn/a0bde95a9064435d9882861ef0ec1748.png#</a> &#x3D;70%x)</p>
<h2 id="3-4-测试用户状态验证接口"><a href="#3-4-测试用户状态验证接口" class="headerlink" title="3.4 测试用户状态验证接口"></a>3.4 测试用户状态验证接口</h2><p>状态验证不需要传参，后端只需要判断 session 里是否存在用户对象就行。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs python">[GET]<br>/login<br></code></pre></td></tr></table></figure>
<h3 id="3-4-2-暂未登录-1"><a href="#3-4-2-暂未登录-1" class="headerlink" title="3.4.2 暂未登录"></a>3.4.2 暂未登录</h3><p>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/6dffb4546af042829996fe476cd89125.png#">https://img-blog.csdnimg.cn/6dffb4546af042829996fe476cd89125.png#</a> &#x3D;70%x)</p>
<h3 id="3-4-1-验证通过"><a href="#3-4-1-验证通过" class="headerlink" title="3.4.1 验证通过"></a>3.4.1 验证通过</h3><p>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/56994bcf5b0b4f8caa79bb6bb87d7cdb.png#">https://img-blog.csdnimg.cn/56994bcf5b0b4f8caa79bb6bb87d7cdb.png#</a> &#x3D;70%x)</p>
<h3 id=""><a href="#" class="headerlink" title=""></a></h3><h2 id="3-5-测试查询用户数据的接口"><a href="#3-5-测试查询用户数据的接口" class="headerlink" title="3.5 测试查询用户数据的接口"></a>3.5 测试查询用户数据的接口</h2><h3 id="3-5-1-测试查询所有用户接口"><a href="#3-5-1-测试查询所有用户接口" class="headerlink" title="3.5.1 测试查询所有用户接口"></a>3.5.1 测试查询所有用户接口</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs python">[GET]<br>/user<br></code></pre></td></tr></table></figure>
<p>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/6af12ca127ba480ea7dc82f0a05cbe10.png#">https://img-blog.csdnimg.cn/6af12ca127ba480ea7dc82f0a05cbe10.png#</a> &#x3D;70%x)</p>
<h3 id="3-5-2-测试查询指定ID用户的接口"><a href="#3-5-2-测试查询指定ID用户的接口" class="headerlink" title="3.5.2 测试查询指定ID用户的接口"></a>3.5.2 测试查询指定ID用户的接口</h3><p>查询指定ID用户，有两种可能：1）用户存在；2）用户不存在</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs python">[GET]<br>/user/:<span class="hljs-built_in">id</span><br></code></pre></td></tr></table></figure>

<ul>
<li><strong>用户存在</strong></li>
</ul>
<p>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/0ffb1ddf840243d2ace331de445323e8.png#">https://img-blog.csdnimg.cn/0ffb1ddf840243d2ace331de445323e8.png#</a> &#x3D;70%x)</p>
<ul>
<li><strong>用户不存在</strong></li>
</ul>
<p>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/1b15aef18c2c46cb825ab0d4a74a0322.png#">https://img-blog.csdnimg.cn/1b15aef18c2c46cb825ab0d4a74a0322.png#</a> &#x3D;80%x)</p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/Python/" class="category-chain-item">Python</a>
  
  
    <span>></span>
    
  <a href="/categories/Python/Web/" class="category-chain-item">Web</a>
  
  

  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/Python/">#Python</a>
      
        <a href="/tags/Flask/">#Flask</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>Python Web 开发 _ Flask 简单实现用户注册、登录、注销、查询接口 _ 初学者案例 _ 简单封装响应数据 _ 使用 Postman 进行接口测试.</div>
      <div>http://example.com/2022/08/04/Python Web 开发 _ Flask 简单实现用户注册、登录、注销、查询接口 _ 初学者案例 _ 简单封装响应数据 _ 使用 Postman 进行接口测试/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>John Doe</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年8月4日</div>
        </div>
      
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/08/11/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%20%E7%AC%94%E8%AE%B02%20_%20%E4%B8%83%E4%B8%AA%E7%BB%93%E6%9E%84%E5%9E%8B%E6%A8%A1%E5%BC%8F%20_%20%E9%80%82%E9%85%8D%E5%99%A8%E6%A8%A1%E5%BC%8F%20_%20%E6%A1%A5%E6%8E%A5%E6%A8%A1%E5%BC%8F%20_%20%E8%A3%85%E9%A5%B0%E5%99%A8%E6%A8%A1%E5%BC%8F%20_%20%E7%BB%84%E5%90%88%E6%A8%A1%E5%BC%8F%20_%20%E4%BB%A3%E7%90%86%E6%A8%A1%E5%BC%8F_%20%E5%A4%96%E8%A7%82%E6%A8%A1%E5%BC%8F%20_%20%E4%BA%AB%E5%85%83%E6%A8%A1%E5%BC%8F%20_%E6%A8%A1%E6%9D%BF%E4%BB%A3%E7%A0%81%E3%80%81%E4%BC%98%E7%BC%BA%E7%82%B9%E3%80%81%E5%BA%94%E7%94%A8%E5%9C%BA%E6%99%AF%E6%80%BB%E7%BB%93%20_%20%E5%9F%BA%E4%BA%8EJava%E5%AE%9E%E7%8E%B0/" title="设计模式 笔记2 _ 七个结构型模式 _ 适配器模式 _ 桥接模式 _ 装饰器模式 _ 组合模式 _ 代理模式_ 外观模式 _ 享元模式 _模板代码、优缺点、应用场景总结 _ 基于Java实现">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">设计模式 笔记2 _ 七个结构型模式 _ 适配器模式 _ 桥接模式 _ 装饰器模式 _ 组合模式 _ 代理模式_ 外观模式 _ 享元模式 _模板代码、优缺点、应用场景总结 _ 基于Java实现</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/08/03/Python%20_%20%E8%BF%9E%E6%8E%A5%20Mysql%20%E6%95%B0%E6%8D%AE%E5%BA%93%20_%20%E5%A2%9E%E5%8A%A0%E3%80%81%E5%88%A0%E9%99%A4%E3%80%81%E4%BF%AE%E6%94%B9%E3%80%81%E6%9B%B4%E6%96%B0%E6%95%B0%E6%8D%AE/" title="Python _ 连接 Mysql 数据库 _ 增加、删除、修改、更新数据">
                        <span class="hidden-mobile">Python _ 连接 Mysql 数据库 _ 增加、删除、修改、更新数据</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
